package com.haier.cloudremote.common;

import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.haier.cloudremote.model.City;

public class CityHandler extends DefaultHandler {
	private static final String SELECTED_CITY_ID = "selectedCityId";
	private static final String SELECTED_CITY_NAME = "selectedCityName";
	private String tagName;
	private int flag = 0;

	private List<City> citys;
	private City city;

	public CityHandler() {
		super();
	}

	public CityHandler(List<City> citys) {
		super();
		this.citys = citys;
	}

	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		tagName = localName;
		if ("map".equals(localName)) {
			city = new City();
		}
		if ("string".equals(localName)) {
			String attr = attributes.getValue(0);
			if (SELECTED_CITY_ID.equals(attr)) {
				flag = 1;
			} else if (SELECTED_CITY_NAME.equals(attr)) {
				flag = 2;
			}
		}
		super.startElement(uri, localName, qName, attributes);
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		if ("string".equals(tagName)) {
			switch (flag) {
			case 1:
				String id = new String(ch, start, length);
				city.setCityId(Integer.parseInt(id));
				break;
			case 2:
				String name = new String(ch, start, length);
				city.setCityName(name);
				break;
			}
		}
		super.characters(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		tagName = "";
		if ("map".equals(localName)) {
			citys.add(city);
		}
		super.endElement(uri, localName, qName);
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
	}

	public List<City> getCitys() {
		return citys;
	}

	public void setCitys(List<City> citys) {
		this.citys = citys;
	}

}
